// basehttp project main.go
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {

	addr := ":8080"
	if len(os.Args) > 1 {
		addr = os.Args[1]
	}
	chS := make(chan string, 100)
	http.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
		chS <- fmt.Sprintf("%s %s", req.Method, req.URL.Path)

		resp.Write([]byte(`hello`))
	})

	go func() {
		sete := make(map[string]int)

		tm := time.NewTicker(1 * time.Second)
		for {
			select {
			case cmd := <-chS:

				if cmd == "clean" {
					sete = make(map[string]int)
					continue
				}

				cnt := sete[cmd]
				sete[cmd] = cnt + 1
			case <-tm.C:
				tt := 0
				for k, v := range sete {
					log.Printf("%s %d\n", k, v)
					tt = v
				}
				log.Printf("total: %d\n", tt)

			}

		}
	}()
	go func() {
		e := http.ListenAndServe(addr, nil)
		if e != nil {
			log.Println(e)
		}
	}()

	cmdrcv := make(chan string, 2)
	go func() {

		for {
			var i string
			fmt.Scanln(&i)
			cmdrcv <- i
		}
	}()
	for {

		cmd := <-cmdrcv
		switch cmd {
		case "exit":
			return
		case "clean":
			chS <- "clean"
			break
		default:
			break
		}
	}

	fmt.Println("Hello World!")
}
